//065959264	Limor Bagizada	040199770	Sarit Chicotay

package Models;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.TreeSet;

import org.omg.CORBA.DynAnyPackage.InvalidValue;

import Base.NGram;

/**
 * 
 * Class implementing the Held-Out discounting model.
 *
 */
public class HeldOutModel extends BaseModel {

	// for printing purpose - for each r - the counter
	private TreeMap<Integer, Integer> r_counter;
	
	/**
	 * Constructor
	 * @param filePath - Initialize model from the given file
	 * @throws IOException
	 * @throws InvalidValue
	 */
	public HeldOutModel(ArrayList<String> content, int nGram) throws IOException, InvalidValue {
		super(content,0.5, nGram);
		r_counter = new TreeMap<Integer, Integer>();
	}

	
	/**
	 * P_HO(x) - calculate the probability of a word (event) that appears r  times in the training according to Held-Out discounting
	 * r - is the count of 
	 */
	public double CalculateProbability(int r) {
		
		// get all words with count r
		TreeSet<NGram> r_words = words_count_r(r);//all the words that appears r times in the training (in case of r=0 all words in test that don't appear in training)
		
		// calculate counter - count appearance of the words in the test corpus
		int counter=0;
		for (NGram r_word: r_words){
			counter+=trainingTest.getCount(r_word);
		}
		
		// calculate denominator - (number of words that appears r times in the training) * (test corpus size)
		double denominator = (double) this.return_N_r(r)*trainingTest.getSize();
		if (denominator == 0)
			return 0;
		
		double result = (double) counter / denominator;
		r_counter.put(r, counter);
		return result;
	}
	
	// get counter for r - count words in test corpus with r appearances in the training corpus
	public int get_r_counter(int r)
	{
		if (!r_counter.containsKey(r))
			return 0;
		
		return r_counter.get(r);
	}

}
